/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { UseButtonGroup } from './types-group';
import { ButtonGroupProps } from '../button-group.props';
import { SetupContext, ref, nextTick } from 'vue';

export function useButtonGroup(props: ButtonGroupProps, context: SetupContext, dpMenu: any, dpBtn: any): UseButtonGroup {
    /* menu size */
    let _menuWidth = 0;
    let _menuHeight = 0;
    const showPanel = ref(props.showPanel);
    const realPlacement = ref(props.realPlacement);
    let mouseEnter = false;

    /* 下拉按钮显示到body中 可改变面板方向  */
    function appendBody() {
        if (dpMenu.value) {
            // 添加到body  便于全部显示
            document.body.appendChild(dpMenu.value);
        }
    }
    /* flag true */
    function changeFlagToTrue() {
        showPanel.value = true;
    }

    /* flag false */
    function changeFlagToFalse() {
        showPanel.value = false;
    }
    /** 鼠标未移入下拉列表后一段时间关闭  */
    function unbindMenuMouseleave() {
        if (showPanel.value && !mouseEnter) {
            setTimeout(() => {
                if (showPanel.value && !mouseEnter) {
                    changeFlagToFalse();
                    mouseEnter = false;
                }
            }, 1000);
        }
    }
    /* 鼠标离开时  关闭menu */
    function mouseLeave() {
        setTimeout(() => {
            if (showPanel.value) {
                // close();
                changeFlagToFalse();
                mouseEnter = false;
            }
        }, 1000);
    }

    /* 绑定下拉面板鼠标进入事件 */
    function bindMenuMouseenter() {
        changeFlagToTrue();
        mouseEnter = true;
    }
    /* 绑定下拉面板鼠标离开事件  */
    function bindMenuMouseleave() {
        mouseLeave();
    }

    /**
     * 确认参照的边界
     */
    function getReferencePosition() {
        let rRight = document.documentElement.clientWidth;
        let rBottom = document.documentElement.clientHeight;
        let rTop = 0;
        let rLeft = 0;
        // 横向参照
        if (props.rectifyReferenceH) {
            const elemH = document.querySelector('props.rectifyReferenceH');
            if (elemH) {
                rRight = elemH.getBoundingClientRect().right;
                rLeft = elemH.getBoundingClientRect().left;
            }
        }
        // 纵向参照
        if (props.rectifyReferenceV) {
            const elemV = document.querySelector('props.rectifyReferenceV');
            if (elemV) {
                rBottom = elemV.getBoundingClientRect().bottom;
                rTop = elemV.getBoundingClientRect().top;
            }
        }
        return { top: rTop, left: rLeft, right: rRight, bottom: rBottom };
    }

    /**
     * 当下拉超出边界时  转换方向,
     * 并未处理，边界不够下拉展示的情况
     * @param btnSize
     */
    function changePlacement(btnSize: any) {
        if (!props.autoRectify) {
            return;
        }
        const referPosition = getReferencePosition();
        const newPlacement = realPlacement;
        if (newPlacement.value.indexOf('bottom') > -1) {
            if (_menuHeight > referPosition.bottom - btnSize.bottom) {
                newPlacement.value = newPlacement.value.replace('bottom', 'top');
            }
        } else if (newPlacement.value.indexOf('top') > -1) {
            if (_menuHeight > btnSize.top - referPosition.top) {
                newPlacement.value = newPlacement.value.replace('top', 'bottom');
            }
        }
        if (newPlacement.value.indexOf('left') > -1) {
            if (_menuWidth > btnSize.left - referPosition.left) {
                newPlacement.value = newPlacement.value.replace('left', 'right');
            }
        } else if (newPlacement.value.indexOf('right') > -1) {
            if (_menuWidth > referPosition.right - btnSize.right) {
                newPlacement.value = newPlacement.value.replace('right', 'left');
            }
        }
        realPlacement.value = newPlacement.value;
    }
    /*
     * 计算的位置区分忒细化
     */
    function changePosition(btnSize: any) {
        let rplacement = '';
        if (props.autoRectify) {
            rplacement = props.rectifyPlacement;
        } else {
            rplacement = realPlacement.value;
        }
        let styleTop = 0;
        let styleLeft = 0;
        if (rplacement.indexOf('top') > -1) {
            styleTop = btnSize.top - _menuHeight;
        } else if (rplacement.indexOf('bottom') > -1) {
            styleTop = btnSize.bottom;
        }
        if (rplacement.indexOf('right') > -1) {
            styleLeft = btnSize.right;
        } else if (rplacement.indexOf('left') > -1) {
            styleLeft = btnSize.left - _menuWidth;
        }
        // 开头
        if (rplacement.indexOf('-top') > -1) {
            styleTop -= btnSize.height;
        } else if (rplacement.indexOf('-bottom') > -1) {
            styleTop += btnSize.height;
        }
        dpMenu.value.style.top = styleTop + 'px';
        dpMenu.value.style.left = styleLeft + 'px';
    }
    /* 动态指定menu在body中的位置 */
    async function setPosition() {
        await nextTick();
        // 下拉按钮
        const btnSize = dpBtn.value.getBoundingClientRect();
        // 下拉面板
        const menuRect = dpMenu.value.getBoundingClientRect();
        _menuHeight = menuRect.height;
        _menuWidth = menuRect.width;
        // 如果要自动纠正方向
        if (props.autoRectify) {
            changePlacement(btnSize);
        }
        changePosition(btnSize);
    }

    /** 展示下拉列表 */
    function clickEvent($event: Event) {
        $event.stopPropagation();
        showPanel.value = !showPanel.value;
        // body添加面板
        if (showPanel.value) {
            appendBody();
            setPosition();
        }
        context.emit('changeState', showPanel.value);
    }

    /* 按钮触发事件 */
    function toggle($event: any, btn: any) {
        $event.stopPropagation();
        if (btn.disabled) return;
        showPanel.value = false;
        context.emit('change', btn.id);
        context.emit('click', btn);
    }

    function getRealPlacement(pment: any) {
        let result = 'bottom-right';
        switch (pment) {
        case 'top':
            result = 'top-right';
            break;
        case 'left':
            result = 'left-bottom';
            break;
        case 'right':
            result = 'right-bottom';
            break;
        case 'bottom':
            result = 'bottom-right';
            break;
        default:
            result = pment;
        }
        realPlacement.value = result;
    }

    return {
        showPanel,
        clickEvent,
        toggle,
        getRealPlacement,
        bindMenuMouseenter,
        unbindMenuMouseleave,
        bindMenuMouseleave
    };
}
